/*
 * Copyright (c) 2021-2021 harkue
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.harkue.pkglock;

import org.harkue.pkglock.integrity.IntegrityGenerator;
import org.harkue.pkglock.vo.PkgLockDependencyVO;
import org.harkue.pkglock.vo.PkgLockVO;
import org.harkue.pkglock.vo.PkgVO;

import java.util.List;

/**
 * Package Lock 工具类
 *
 * @author harkue
 * @date 2021/12/18
 */
public class PkgLockUtils {
    private final IntegrityGenerator integrityGenerator;

    public PkgLockUtils() {
        this.integrityGenerator = new IntegrityGenerator();
    }

    /**
     * 根据现有的Package Lock配置，合并输入的依赖包信息， 生成新的Package Lock配置
     * <p>
     * 特殊场景不能被覆盖: 当新包名与旧包名不一致时
     * 旧包名： ztree
     * 新包名： @ztree/ztree_v3
     * </p>
     *
     * @param pkgLock 现有的Package Lock配置
     * @param pkgList 输入的依赖包信息
     * @return 新的Package Lock配置
     */
    public PkgLockVO merge(PkgLockVO pkgLock, List<PkgVO> pkgList) {
        if (pkgList == null || pkgList.isEmpty()) {
            return pkgLock;
        }

        for (PkgVO pkg : pkgList) {
            // 根据package name找到其在Package Lock配置中的位置
            PkgLockDependencyVO target = pkgLock.find(pkg.getName());
            mergeDependency(target, pkg);
        }

        return pkgLock;
    }

    /**
     * 合并依赖的信息，包括版本、链接、Hash值
     *
     * @param dependency 被匹配的依赖配置
     * @param pkg        新包信息
     */
    public void mergeDependency(PkgLockDependencyVO dependency, PkgVO pkg) {
        String oldVersion = dependency.getVersion();
        String newVersion = pkg.getVersion();

        // 合并版本
        dependency.setVersion(newVersion);

        // 更新下载链接
        String oldUrl = dependency.getResolved();
        String newUrl = oldUrl.replaceAll(oldVersion, newVersion);
        dependency.setResolved(newUrl);

        String newIntegrity = integrityGenerator.genIntegrity(newUrl, PkgConstants.SHA1);
        dependency.setIntegrity(newIntegrity);
    }
}
